package MainApp;

import java.util.*;

import DataCenter.ConfigAccessor;
import Service.ServiceThread;

public class MainThread extends Thread {

	private static final String TAG = "Client has been quited.";
	private static final String COMMAND_ERROR = "Error Command : ";
	private static final String INPUT_HINT = "Please enter the command:";

	Scanner input;
	
	HashSet<String> commands;
	
	ServiceThread blockingThread;

	private boolean ifStopThread = true;
	
	public MainThread() {
		this.input = new Scanner(System.in);
		this.commands = ConfigAccessor.sharedInstance().getCommandSet();
	}

	@Override
	public void run() {
		super.run();
		
		while (ifStopThread) {
			String inputContent = getInputContent();
			if (isInputContentCommand(inputContent)) {
				handleCommand(inputContent);
			}
			else
				System.out.println(COMMAND_ERROR + inputContent);
		}
		
		System.out.println(TAG);
	}
	
	private String getInputContent() {
		System.out.println(INPUT_HINT);
		String inputContent = input.nextLine();
		return inputContent.trim();
	}
	
	private boolean isInputContentCommand(String inputContent) {
		return commands.contains(inputContent);
	}
	
	private void handleCommand(String command) {
		if (command.equals("Exit"))
			ifStopThread = false;
		else {
			String className = "ServiceThread." + command + "Thread";
			blockingThread = createThreadFromClassName(className);
			activeThreadAndBlockSelfThread(blockingThread);
		}
	}
	
	private ServiceThread createThreadFromClassName(String className) {
		ServiceThread serviceThread;
		
		try {
			serviceThread = (ServiceThread) Class.forName(className).newInstance();
		} catch (InstantiationException e) {
			serviceThread = null;
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			serviceThread = null;
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			serviceThread = null;
			e.printStackTrace();
		}
		return serviceThread;
	}

	private void activeThreadAndBlockSelfThread(ServiceThread blockingThread) {
		Thread serviceThread = new Thread(blockingThread);
		serviceThread.start();
		
		synchronized(blockingThread) {
			try {
				blockingThread.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}
